package cn.gson.crm.controller.teaching;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ChutiDao;
import cn.gson.crm.model.dao.ClassDao;
import cn.gson.crm.model.dao.ExercisesDao;
import cn.gson.crm.model.dao.OutlineDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.dao.StudnetClassShadowDao;
import cn.gson.crm.model.dao.UserDao;
import cn.gson.crm.model.dao.WorkJinDuDao;
import cn.gson.crm.model.dao.ZhangJieDao;
import cn.gson.crm.model.entity.Chuti;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.DaGang;
import cn.gson.crm.model.entity.Emp;
import cn.gson.crm.model.entity.Exercises;
import cn.gson.crm.model.entity.Grade;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.StudnetClassShadow;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.entity.WorkJinDu;
import cn.gson.crm.model.entity.ZhangJie;
import cn.gson.crm.model.mapper.ClassesMapper;
import cn.gson.crm.model.mapper.DeptMapper;
import cn.gson.crm.model.mapper.StudentMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/classes")
@Log4j
public class ClassesController {
	@Autowired
	private ClassesMapper claMapper;
	
	@Autowired
	private StudentMapper stuMapper;
	
	@Autowired
	private DeptMapper empMapper;
	
	@Autowired
	private ClassDao claDao;
	
	@Autowired
	private StudentDao stuDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private StudnetClassShadowDao scsDao;
	
	@Autowired
	private OutlineDao olDao;
	
	@Autowired
	private ZhangJieDao zjDao;
	
	@Autowired
	private  ExercisesDao eiDao;
	
	@Autowired
	private  ChutiDao ctDao;
	
	@Autowired
	private WorkJinDuDao jdDao;
	/**
	 * 查询班级列表datagrid
	 * @param cla
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String,Object> index(Classes cla, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Classes> pageData = claMapper.listClasses(cla);
		PageInfo<Classes> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 添加班级
	 * @param emp
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "addclass", "addclass/{id}" })
	public String form(Emp emp,@PathVariable(name = "id", required = false) Long id, Model model) {
		List<Student> stus = new ArrayList<>();
		if (id != null) {
			Classes c = claDao.findOne(id);
			if (c != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("cla", c);
				List<Long> stuids = claMapper.returnAllclastuid(id);
				for(int i=0;i<stuids.size();i++) {
					Student stu = stuDao.findOne(stuids.get(i));
					stus.add(stu);
				}
			}
		}
		
		List<Emp> jy = claMapper.listJy(emp);
		List<Emp> bzr = claMapper.listBzr(emp);
		model.addAttribute("jy", jy);
		model.addAttribute("bzr", bzr);
		model.addAttribute("stus", stus);
		return "classes/addclass";
	}
	
	/**
	 * 保存班级
	 * @param cla
	 * @param br
	 * @return
	 */
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(@Valid Classes cla, BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			Classes  c = claDao.findByClassName(cla.getClassName());
			if(cla.getId() == null) {
				if(c !=null) {
					obj.put("message", "不能添加相同的班级！");
				}else {
					cla.setDelete(true);
					cla.setStatus("正式");
					claDao.save(cla);
					obj.put("success", true);
					List<Classes> pageData = claMapper.listClasses(cla);
					StudnetClassShadow scs = new StudnetClassShadow();
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
					scs.setDelete(true);
					scs.setClassType(cla.getClassType());
					scs.setOpenShadowTime(df.format(cla.getOpenTime()));
					scs.setShadowClassTeacher(cla.getClassTeacherEmp().getName());
					scs.setShadowId(pageData.get(pageData.size()-1).getId());
					scs.setShadowName(cla.getClassName());
					scs.setShadowNum(cla.getNum());
					scs.setShadowTeacher(cla.getTeacherEmp().getName());
					scs.setStates("正式");
					scsDao.save(scs);
					}
			}else {
				Classes clas = claDao.findOne(cla.getId());
				cla.setDelete(true);
				claMapper.editClass(cla);
				obj.put("success", true);
				Long scsid = claMapper.obtainscsid(cla.getId(),clas.getClassName());
				
				StudnetClassShadow scs = new StudnetClassShadow();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
				scs.setId(scsid);
				scs.setDelete(true);
				scs.setClassType(cla.getClassType());
				scs.setOpenShadowTime(df.format(cla.getOpenTime()));
				scs.setShadowClassTeacher(cla.getClassTeacherEmp().getName());
				scs.setShadowId(cla.getId());
				scs.setShadowName(cla.getClassName());
				scs.setShadowNum(cla.getNum());
				scs.setShadowTeacher(cla.getTeacherEmp().getName());
				scs.setMonitor(cla.getStudent().getName());
				scs.setStates("正式");
				scsDao.save(scs);
			}		
		}
		return obj;
	}
	/**
	 * 删除班级
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Classes c;
		StudnetClassShadow s;
		if(id != null && (c = claDao.findOne(id)) !=null ) {
			c.setDelete(false);
			claDao.save(c);
			
			Long scsid = claMapper.obtainscsid(c.getId(),c.getClassName());
			
			if(scsid != null && (s = scsDao.findOne(scsid)) != null) {
				log.info("删除影子表");
				s.setDelete(false);
				scsDao.save(s);
			}

			obj.put("success", true);
		}else {
			obj.put("message", "此学生不存在");
		}
		return obj;
	}
	
	
	/**
	 * 打开班级详情界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/formal_student/{id}")
	public String formal_student(@PathVariable(name = "id", required = false) Long id,Model model) {
		model.addAttribute("classid", id);
		return "/classes/formal_student";
	}
	
	/**
	 * 通过班级id返回班级学生中间表的所有学生id
	 * @param classid
	 * @param cla
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/studentlist/{id}")
	@ResponseBody
	public Map<String,Object> studentlist(@PathVariable(name = "id", required = false) Long classid,Classes cla, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		List<Long> stuids = claMapper.returnAllclastuid(classid);
		List<Student> pageData = new ArrayList<>();
		Student stus = new Student();
		
		for(int i = 0;i<stuids.size();i++) {
			log.info(stuids.get(i));
			Long sid = stuids.get(i);
			stus.setId(sid);
			Student stu = claMapper.clastulist(stus);
			pageData.add(i, stu);
		}
		PageHelper.startPage(pageNum, pageSize);
		PageInfo<Student> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 获取正式树状班级
	 */
	@RequestMapping("stuclatree")
	@ResponseBody
	public Map<String,Object> list(StudnetClassShadow scs,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		List<StudnetClassShadow>  diss = claMapper.scstree(scs);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		//查询所有没有父id的分配记录
		List<StudnetClassShadow>  dis = claMapper.scstree(scs);
		obj.put("total", diss.size());
		obj.put("rows", dis);
		return obj;
	}
	/**
	 * 获取毕业树状班级
	 */
	@RequestMapping("graduatestuclatree")
	@ResponseBody
	public Map<String,Object> graduatelist(StudnetClassShadow scs,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		List<StudnetClassShadow>  diss = claMapper.scstree(scs);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		//查询所有没有父id的分配记录
		List<StudnetClassShadow>  dis = claMapper.graduatescstree(scs);
		obj.put("total", diss.size());
		obj.put("rows", dis);
		return obj;
	}
	/**
	 * 班级毕业
	 */
	@RequestMapping("graduation/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> graduation(@PathVariable(name="id",required=false) Long id){
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Classes cla = claDao.findOne(id);
		cla.setStatus("已毕业");
		//修改班级状态
		claMapper.editClass(cla);
		//修改影子表状态
		Long scsid = claMapper.obtainscsid(cla.getId(),cla.getClassName());
		if(scsid != null) {
			StudnetClassShadow scs = scsDao.findOne(scsid);
			scs.setStates("已毕业");
			scsDao.save(scs);
			List<Long> stuid = claMapper.returnAllclastuid(id);
			for(int i=0;i<stuid.size();i++) {
				Student stu = stuDao.findOne(stuid.get(i));
				stu.setState("毕业");
				stuDao.save(stu);
			}
			obj.put("success", true);
		}else {
			obj.put("message", "毕业失败");
		}
		return obj;
	}
	/**
	 * 打开转移班级界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping("transferclass/{id}")
	@Transactional
	public String transferclass(@PathVariable(name = "id", required = false)Long id,Model model) {
		List<StudnetClassShadow> cla = claMapper.listclass();
		Long claid = claMapper.returnclassid(id);
		
		Classes classes = claDao.findOne(claid);
		model.addAttribute("cla", cla);
		model.addAttribute("classes", classes);
		model.addAttribute("sid", id);
		return "classes/transferclass";
	}
	/**
	 * 保存转移班级
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("savetransferclass/{sid}/{newcla}")
	@Transactional
	@ResponseBody
	public Map<String,Object> savetransferclass(@PathVariable(name = "sid", required = false)Long sid,
									@PathVariable(name = "newcla", required = false)Object newcla) {
		Map<String, Object> savastucla = new HashMap<String, Object>();
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Student stu = stuDao.findOne(sid);
		if(stu != null) {
			if(stu.getShiftStudent() == 0) {
				stu.setShiftStudent(1);
				stuDao.save(stu);
				//删除中间表学生
				claMapper.deletesid(sid);
				StudnetClassShadow scs = claMapper.selectstuName((String) newcla);
				Long[] students = new Long[1];
				students[0] = sid;
				savastucla.put("classId", scs.getShadowId());
				savastucla.put("stuId", Arrays.asList(students));
				//为学生班级中间添加数据。
				claMapper.saveclassOrStudent(savastucla);
				StudnetClassShadow s = new StudnetClassShadow();
				s.setShadowId(sid);
				s.setShadowName(stu.getName());
				StudnetClassShadow scs2 = claMapper.selectstuid(s);
				scs2.setParent(scs);
				scsDao.save(scs2);
				obj.put("success", true);
			}else {
				obj.put("message","该学生已转过班级" );
			}
		}
		return obj;
	}
	/**
	 * 打开添加学员界面
	 * @param student
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("addfamentsutdent/{id}")
	public String addfamentsutdent(Student student,@PathVariable(name = "id", required = false) Long id,Model model) {
		Long stunum = claMapper.countclassstudent(id);
		Classes classmessage = claMapper.selectIdclassmessage(id);
		List<Student> stu = stuMapper.famentstuList(student);
		int g=0;
		int d=0;
		for(int i = 0;i<stu.size();i++) {
			if(stu.get(i).getEducation().equals("高中生")) {
				g++;
			}else {
				d++;
			}
		}
		model.addAttribute("stunum", stunum);
		model.addAttribute("dfbstuall", stu.size());
		model.addAttribute("dfbstug", g);
		model.addAttribute("dfbstud", d);
		model.addAttribute("classmessage", classmessage);
		return "classes/addfamentsutdent";
	}
	
	
	Map<String,Object> stuobj = new HashMap<String, Object>();
	List<Student> studfb = new ArrayList<Student>();
	Long tags;
	/**
	 * 左边移动删除左边的集合数据
	 * @param student
	 * @return
	 */
	@RequestMapping("studentlist")
	@ResponseBody
	public Map<String,Object> studentlist(
			Student student){
		Map<String,Object> obj = new HashMap<String, Object>();
		List<Student> stu = stuMapper.famentstuList(student);
		if(stuobj.size() != 0 && studfb != null) {
			stu.removeAll(studfb);
		}
		obj.put("total", stu.size());
		obj.put("rows", stu);
		return obj;
	}
	/**
	 * 右移动
	 * @param check
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("famentstudentlist/{ids}/{tag}")
	@ResponseBody
	public Map<String,Object> famentstudentlist(
			@PathVariable(name = "ids", required = false) Long[] check,
			@PathVariable(name = "tag", required = false) Long tag){
		List<Student> stuleft = new ArrayList<Student>();
		tags = tag;
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		for(int i = 0;i<check.length;i++) {
			Student stu = stuMapper.studentid(check[i]);
			stuleft.add(i, stu);
		}
		if(stuleft.size()>0) {
			if(tag == 1) {
				studfb.removeAll(stuleft);
			}else {
			studfb.addAll(stuleft);
			}
			obj.put("success", true);
			stuobj.put("total", studfb.size());
			stuobj.put("rows", studfb);
		}else {
			obj.put("message", "数据存入失败");
		}
		return obj;
	}
	/**
	 * 将右边集合返回到右边的表格
	 * @return
	 */
	@RequestMapping("famentstudent")
	@ResponseBody
	public Map<String,Object> fament(){
		if(stuobj.size() == 0) {
			return null;
		}else {
		return stuobj;
		}
	}
	/**
	 * 清楚班级添加学生使用的全局变量
	 */
	@RequestMapping("stuobjclear")
	@ResponseBody
	public void stuobjclear(){
		stuobj.clear();
		studfb.clear();
	}
	
	/**
	 * 保存要添加的学生并保存到班级学生影子表
	 * @param id
	 * @return
	 */
	@RequestMapping("saveaddstu/{id}")
	@ResponseBody
	@Transactional
	public Map<String, Object> saveaddstu(@PathVariable(name = "id", required = false) Long id){
		Map<String, Object> savastucla = new HashMap<String, Object>();
		Map<String, Object> obj = new HashMap<String, Object>();
		Classes cla = claDao.findOne(id);
		Long stunum=claMapper.countclassstudent(id);
		obj.put("success", false);
		if(studfb.size() == 0) {
			obj.put("message", "请选择要添加的学生！");
		}else if(studfb.size()+stunum > cla.getNum()) {
			obj.put("message", "这个班级人数已满请修改班级上限人数再来添加学生");
		}else {
			
			Long[] students = new Long[studfb.size()];
			for(int i = 0;i<studfb.size();i++) {
				students[i] =  studfb.get(i).getId();
				studfb.get(i).setState("在读");;
			}
			savastucla.put("classId", id);
			savastucla.put("stuId", Arrays.asList(students));
			//为学生班级中间添加数据。
			claMapper.saveclassOrStudent(savastucla);
			for(int i = 0;i<studfb.size();i++) {
				claMapper.editstudent(studfb.get(i));
			}
			//获取班级信息
			Classes clas = claDao.findOne(id);
			if(clas != null) {
				//获取父类id
				Long scsid = claMapper.obtainscsid(clas.getId(),clas.getClassName());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
				for(int i = 0;i<studfb.size();i++) {
					User user = new User();
					//获取用户是否有重复
					int count=empMapper.countAccount(studfb.get(i).getName()+"%");
					if (count>=1) {
						user.setAccount(studfb.get(i).getName()+count);
						user.setName(studfb.get(i).getName());
						user.setPassword("aaaaaa");
						user.setStudent(studfb.get(i));;
						user.setDelete(true);
						user.setEnable(true);
						userDao.save(user);
					}else {
						user.setPassword("aaaaaa");
						user.setAccount(studfb.get(i).getName());
						user.setName(studfb.get(i).getName());
						user.setStudent(studfb.get(i));
						user.setDelete(true);
						user.setEnable(true);
						userDao.save(user);
					}
					StudnetClassShadow scs = new StudnetClassShadow();
					StudnetClassShadow parent = scsDao.findOne(scsid);
					scs.setDelete(true);
					scs.setShadowId(studfb.get(i).getId());
					scs.setClassType(studfb.get(i).getGender());
					scs.setOpenShadowTime(df.format(new Date()));
					scs.setShadowName(studfb.get(i).getName());
					scs.setShadowClassTeacher(parent.getShadowClassTeacher());
					scs.setShadowNum(null);
					scs.setShadowTeacher(parent.getShadowTeacher());
					scs.setParent(parent);
					scsDao.save(scs);
				}
				obj.put("success", true);
			}else {
				obj.put("message", "没有找到班级");
			}
		}
		return obj;
	}
	/**
	 * 打开添加阶段的界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/addoutline","/addoutline/{id}"})
	public String addoutline(@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			DaGang ol = olDao.findOne(id);
				//如果是编辑，则将原有学生信息传回表单页面
				if(ol!=null) {
					model.addAttribute("ol", ol);
				}
		}
		return "classes/addoutline";
	}
	/**
	 * 保存阶段
	 * @param dg
	 * @param br
	 * @return
	 */
	@RequestMapping("/saveoutline")
	@ResponseBody
	@Transactional
	public Map<String,Object> saveoutline(@Valid DaGang dg,BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			dg.setDeleted(true);
			olDao.save(dg);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除大纲
	 * @param id
	 * @return
	 */
	@GetMapping("outlinedelete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> outlinedelete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		DaGang ol = new DaGang();
		if(id != null && (ol = olDao.findOne(id)) !=null ) {
			ol.setDeleted(false);
			olDao.save(ol);
			obj.put("success", true);
		}else {
			obj.put("message", "此阶段不存在");
		}
		return obj;
	}
	/**
	 * 打开章节界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("chapter/{id}")
	public String chapter(@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			DaGang ol = olDao.findOne(id);
			if(ol != null) {
				model.addAttribute("dg", ol);
			}
			List<ZhangJie> zjs = claMapper.allchaterlist(id);
			model.addAttribute("zjs", zjs);
		}
		return "classes/chapter";
	}
	/**
	 * 打开添加章节的界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/addchater","/addchater/{id}"})
	public String addchater(@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			ZhangJie zjs = zjDao.findOne(id);
				//如果是编辑，则将原有学生信息传回表单页面
				if(zjs!=null) {
					model.addAttribute("zjs", zjs);
				}
		}
		return "classes/addchater";
	}
	/**
	 * 保存添加的章节
	 * @param dgid
	 * @param zj
	 * @param br
	 * @return
	 */
	@RequestMapping("/savechater/{dgid}")
	@ResponseBody
	@Transactional
	public Map<String,Object> savechater(@PathVariable(name = "dgid", required = false)Long dgid,@Valid ZhangJie zj,BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			DaGang ol = olDao.findOne(dgid);
			zj.setDeleted(true);
			zj.setDagang(ol);
			zjDao.save(zj);
			obj.put("success", true);
		}
		return obj;
	}
	
	/**
	 * 删除章节
	 * @param id
	 * @return
	 */
	@GetMapping("chaterdelete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> chaterdelete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		ZhangJie zj = new ZhangJie();
		if(id != null && (zj = zjDao.findOne(id)) !=null ) {
			zj.setDeleted(false);
			zjDao.save(zj);
			obj.put("success", true);
		}else {
			obj.put("message", "此章节不存在");
		}
		return obj;
	}
	/**
	 * 打开试题界面
	 * @param exercises
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("exercises/{id}")
	public String exercises(Exercises exercises,@PathVariable(name = "id", required = false)Long id, Model model) {
		//判断章节是否为空
		if(id != null){
			ZhangJie zj = zjDao.findOne(id);
			if(zj != null){
				model.addAttribute("zj", zj);
				exercises.setZhangJie(zj);
				exercises.setType("选择题");
				List<Exercises> choice = claMapper.allexerciseslist(exercises);
				exercises.setType("判断题");
				List<Exercises> option = claMapper.allexerciseslist(exercises);
				
				exercises.setType("编程题");
				List<Exercises> program = claMapper.allexerciseslist(exercises);
				//将获取的试题集合存进model
				model.addAttribute("choice", choice);
				model.addAttribute("option", option);
				model.addAttribute("program", program);
			}
			
		}
		return "classes/exercises";
	}
	/**
	 * 打开添加选择题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping({"choice/{zjid}","choice/{zjid}/{xtid}"})
	@Transactional
	public String choice(@PathVariable(name = "zjid", required = false)Long zjid,
			@PathVariable(name = "xtid", required = false)Long xtid,Model model) {
		if(zjid != null) {
			ZhangJie zj = zjDao.findOne(zjid);
			if(zj != null){
				model.addAttribute("zj", zj);
			}
		}
		if(xtid != null) {
			Exercises xt = eiDao.findOne(xtid);
			if(xt != null){
				model.addAttribute("xt", xt);
			}
		}
		return "classes/choice";
	}
	/**
	 * 保存添加的选择题
	 * @param exercises
	 * @param br
	 * @return
	 */
	@RequestMapping("saveaddchoise")
	@ResponseBody
	@Transactional
	public  Map<String,Object> saveaddchoise(@Valid Exercises exercises,BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			exercises.setDeleted(true);
			exercises.setType("选择题");
			if(exercises.getAnswer().indexOf(",") != -1) {
				exercises.setAnswer(exercises.getAnswer().replaceAll(",", ""));
			}
			eiDao.save(exercises);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除选择题
	 * @param id
	 * @return
	 */
	@GetMapping("choisedelete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> choisedelete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Exercises ei = new Exercises();
		if(id != null && (ei = eiDao.findOne(id)) !=null ) {
			ei.setDeleted(false);
			eiDao.save(ei);
			obj.put("success", true);
		}else {
			obj.put("message", "此选择题不存在");
		}
		return obj;
	}
	/**
	 * 打开添加判断题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping({"opinion/{zjid}","opinion/{zjid}/{xtid}"})
	@Transactional
	public String opinion(@PathVariable(name = "zjid", required = false)Long zjid,
			@PathVariable(name = "xtid", required = false)Long xtid,Model model) {
		if(zjid != null) {
			ZhangJie zj = zjDao.findOne(zjid);
			if(zj != null){
				model.addAttribute("zj", zj);
			}
		}
		if(xtid != null) {
			Exercises xt = eiDao.findOne(xtid);
			if(xt != null){
				model.addAttribute("xt", xt);
			}
		}
		return "classes/opinion";
	}
	/**
	 * 保存添加的判断题
	 * @param exercises
	 * @param br
	 * @return
	 */
	@RequestMapping("saveaddopinion")
	@ResponseBody
	@Transactional
	public  Map<String,Object> saveaddopinion(@Valid Exercises exercises,BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			exercises.setDeleted(true);
			exercises.setType("判断题");
			eiDao.save(exercises);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除判断题
	 * @param id
	 * @return
	 */
	@GetMapping("opiniondelete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> opiniondelete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Exercises ei = new Exercises();
		if(id != null && (ei = eiDao.findOne(id)) !=null ) {
			ei.setDeleted(false);
			eiDao.save(ei);
			obj.put("success", true);
		}else {
			obj.put("message", "此判断题不存在");
		}
		return obj;
	}
	
	/**
	 * 打开编程题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping({"program/{zjid}","program/{zjid}/{xtid}"})
	@Transactional
	public String program(@PathVariable(name = "zjid", required = false)Long zjid,
			@PathVariable(name = "xtid", required = false)Long xtid,Model model) {
		if(zjid != null) {
			ZhangJie zj = zjDao.findOne(zjid);
			if(zj != null){
				model.addAttribute("zj", zj);
			}
		}
		if(xtid != null) {
			Exercises xt = eiDao.findOne(xtid);
			if(xt != null){
				model.addAttribute("xt", xt);
			}
		}
		return "classes/program";
	}
	
	/**
	 * 保存添加的编程题
	 * @param exercises
	 * @param br
	 * @return
	 */
	@RequestMapping("saveaddprogram")
	@ResponseBody
	@Transactional
	public  Map<String,Object> saveaddprogram(@Valid Exercises exercises,BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			exercises.setDeleted(true);
			exercises.setType("编程题");
			eiDao.save(exercises);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除编程题
	 * @param id
	 * @return
	 */
	@GetMapping("programdelete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> programdelete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Exercises ei = new Exercises();
		if(id != null && (ei = eiDao.findOne(id)) !=null ) {
			ei.setDeleted(false);
			eiDao.save(ei);
			obj.put("success", true);
		}else {
			obj.put("message", "此判断题不存在");
		}
		return obj;
	}
	
	/**
	 * 打开转移试题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping("transferexercises/{zjid}/{xtid}")
	@Transactional
	public String transferexercises(@PathVariable(name = "zjid", required = false)Long zjid,
			@PathVariable(name = "xtid", required = false)Long xtid,Model model) {
		if(zjid != null) {
			ZhangJie zj = zjDao.findOne(zjid);
			if(zj != null){
				model.addAttribute("zj", zj);
			}
		}
		if(xtid != null) {
			Exercises xt = eiDao.findOne(xtid);
			if(xt != null){
				model.addAttribute("xt", xt);
			}
		}
		return "classes/transferexercises";
	}
	/**
	 * 打开生成试题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping("test_paper")
	@Transactional
	public String test_paper(@PathVariable(name = "checkeds", required = false)Long[] checkeds, @Valid Chuti ct,BindingResult br,Model model) {
		return "classes/test_paper";
	}
	
	/**
	 * 打开生成试题界面
	 * @param zjid
	 * @param xtid
	 * @param model
	 * @return
	 */
	@RequestMapping({"test_papers/{checkeds}"})
	@ResponseBody
	public Map<String,Object> test_papers(Exercises exercises,HttpSession session,@PathVariable(name = "checkeds", required = false)Long[] checkeds, @Valid Chuti ct,BindingResult br,Model model) {
		Map<String,Object> obj = new HashMap<String, Object>();
		List<Exercises> crandom = new ArrayList<Exercises>();
		List<Exercises> orandom = new ArrayList<Exercises>();
		List<Exercises> prandom = new ArrayList<Exercises>();
		obj.put("success", false);
		//保存随机生成的题目id
		Long id = null;
		for(int i=0;i<checkeds.length;i++) {
			id = checkeds[i];
			ZhangJie zj = zjDao.findOne(id);
			if(zj != null){
				exercises.setZhangJie(zj);
				exercises.setType("选择题");
				List<Exercises> choice = claMapper.allexerciseslist(exercises);
				exercises.setType("判断题");
				List<Exercises> option = claMapper.allexerciseslist(exercises);
				exercises.setType("编程题");
				List<Exercises> program = claMapper.allexerciseslist(exercises);
				crandom.addAll(choice);
				orandom.addAll(option);
				prandom.addAll(program);
				if(i==checkeds.length-1) {
					List<Exercises> choicerandom = randomexercises(crandom,ct.getChooseCount());
					List<Exercises> optionrandom = randomexercises(orandom,ct.getOpinionCount());
					List<Exercises> programrandom = randomexercises(prandom,ct.getProgramCount());
					session.setAttribute("choice", choicerandom);
					session.setAttribute("option", optionrandom);
					session.setAttribute("program", programrandom);
				}
			}
		}
		List<ZhangJie> zj = new ArrayList<>();
		for(int i=0;i<checkeds.length;i++) {
			ZhangJie zjs = zjDao.findOne(checkeds[i]);
			zj.add(zjs);
		}
		zj=removeDuplicate(zj);
		obj.put("success", true);
		session.setAttribute("ct", ct);
		session.setAttribute("zj", zj);
		return obj;
	}
	//去掉集合中相同数据
	private List<ZhangJie>  removeDuplicate(List<ZhangJie> list)  {       
		  for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {       
		      for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {       
		           if  (list.get(j).equals(list.get(i)))  {       
		              list.remove(j);       
		            }        
		        }        
		      }        
		    return list;       
		}
	/**
	 * 单个章节随机生成题目的方法
	 * @param choice这个章节所有题目集合
	 * @param count 题目数量
	 * @return
	 */
	private List<Exercises> randomexercises(List<Exercises> choice,int count){
		List<Exercises> randomid = new ArrayList<Exercises>();
		 Random random = new Random();
		 if(count>choice.size()) {
			 count=choice.size();
		 }
		 int max=choice.size()-1;
	     int min=0;
	     int s=0;
		for(int j=0;j<count;j++) {
			int tag = randomid.size();
			 while(true) {
				 //随机生成一个选择题试题list集合下标
				  s = random.nextInt(max - min + 1) + min;
				 if(randomid.size() == 0) {
					 randomid.add(0, choice.get(s)); 
				 }else{
					 for(int c=0;c<randomid.size();c++) {
						 if(randomid.get(c).getId() == choice.get(s).getId()){
							 break;
						 }else if(c == randomid.size()-1){
							 randomid.add(j,choice.get(s));
						 }
					 }
				 }
				 if(tag<randomid.size()) {
					 	break;
				 }
			 }
		}
		return randomid;
	}
	/**
	 * 保存自动生成的试卷
	 * @param exercises
	 * @param br
	 * @return
	 */
	@RequestMapping("saveexercises")
	@ResponseBody
	@Transactional
	public  Map<String,Object> saveexercises(HttpSession session) {
		Map<String,Object> obj = new HashMap<String, Object>();
		Map<String, Object> savaworkorexce = new HashMap<String, Object>();
		obj.put("success",false);
		List<Exercises> choice =  (List<Exercises>) session.getAttribute("choice");
		List<Exercises> option = (List<Exercises>) session.getAttribute("option");
		List<Exercises> program = (List<Exercises>) session.getAttribute("program");
		choice.addAll(option);
		choice.addAll(program);
		if(choice.size()==0) {
			obj.put("message","没有试题");
		}else {
			obj.put("success",true);
			Chuti ct = (Chuti) session.getAttribute("ct");
			ct.setDelete(true);
			ctDao.save(ct);
			//获取作业id
			List<Long> ids = claMapper.selectexceid();
			//获取所有的试题id
			Long[] choices = new Long[choice.size()];
			for(int j = 0;j<choice.size();j++) {
				choices[j] = choice.get(j).getId();
			}
			Long wid = ids.get(ids.size()-1);
			savaworkorexce.put("workId", ids.get(ids.size()-1));
			savaworkorexce.put("exceId", Arrays.asList(choices));
			//为习题作业中间添加数据。
			claMapper.saveworkAndexce(savaworkorexce);
			
			for(int c = 0;c<ct.getCla().size();c++) {
				//获取派发班级的所有学生id
				Long cid = ct.getCla().get(c).getId();
				List<Long> stuids = claMapper.returnAllclastuid(cid);
				//为作业进度添加作业id
				for(int i = 0;i<stuids.size();i++) {
					Student student = stuDao.findOne(stuids.get(i));
					//获取不到出题
					List<Chuti> work = (List<Chuti>) ctDao.findAll();
					WorkJinDu workjd = new WorkJinDu();
					workjd.setAllScore(null);
					workjd.setState("未做");
					workjd.setWork(work.get(work.size()-1));
					workjd.setStudent(student);
					jdDao.save(workjd);
				}
			}
			session.removeAttribute("choice");
			session.removeAttribute("option");
			session.removeAttribute("program");
			session.removeAttribute("ct");
		}
		return obj;
	}
	@RequestMapping("tx/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> tx(@PathVariable(name = "id", required = false)Long id){
		Map<String,Object> obj = new HashMap<String, Object>();
		Student stu = stuDao.findOne(id);
		if(stu == null) {
			obj.put("success", false);
			obj.put("message", "学生不见了");
		}else {
			stu.setState("退学");
			stuDao.save(stu);
			StudnetClassShadow s = new StudnetClassShadow();
			s.setShadowId(stu.getId());
			s.setShadowName(stu.getName());
			StudnetClassShadow scs = claMapper.selectstuid(s);
			scsDao.delete(scs);
			obj.put("success", true);
		}
		return obj;
	}
	@RequestMapping("deletestu/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> deletestu(@PathVariable(name = "id", required = false)Long id){
		Map<String,Object> obj = new HashMap<String, Object>();
		Student stu = stuDao.findOne(id);
		if(stu == null) {
			obj.put("success", false);
			obj.put("message", "学生不见了");
		}else {
			stu.setState("开除");
			stuDao.save(stu);
			StudnetClassShadow s = new StudnetClassShadow();
			s.setShadowId(stu.getId());
			s.setShadowName(stu.getName());
			StudnetClassShadow scs = claMapper.selectstuid(s);
			scsDao.delete(scs);
			obj.put("success", true);
		}
		return obj;
	}
}
